import { reqgetcate, reqgetgoods } from "../../http/api";
//state
const initState = {
  cate: [],
  n: 0,
  goods: [],
};

//action type
const TYPES = {
  CATE_CHANGE_CATE: "CATE_CHANGE_CATE",
  CATE_CHANGE_N: "CATE_CHANGE_N",
  CATE_CHANGE_GOODS: "CATE_CHANGE_GOODS",
};

//reducer
const reducer = (state = initState, action) => {
  switch (action.type) {
    case TYPES.CATE_CHANGE_CATE:
      return {
        ...state,
        cate: action.cate,
      };
    case TYPES.CATE_CHANGE_N:
      return {
        ...state,
        n: action.n,
      };
    case TYPES.CATE_CHANGE_GOODS:
      return {
        ...state,
        goods: action.goods,
      };
    default:
      return state;
  }
};

//action creator
export const actions = {
  changeCate: (cate) => ({ type: TYPES.CATE_CHANGE_CATE, cate }),
  reqCate: () => (dispatch, getState) => {
    reqgetcate().then((res) => {
      dispatch(actions.changeCate(res.data.list));
    });
  },
  changeN: (n) => ({ type: TYPES.CATE_CHANGE_N, n }),
  // changeN: (n,id) => (dispatch,getState) =>{
  //    dispatch(actions.reqGoods(id))
  //     return ({ type: TYPES.CATE_CHANGE_N, n,id})
  // },
  changeGoods: (goods) => ({ type: TYPES.CATE_CHANGE_GOODS, goods }),
  reqGoods: (fid) => (dispatch, getState) => {
    reqgetgoods({ fid }).then((res) => {
      dispatch(actions.changeGoods(res.data.list));
    });
  },
};

//selector导出数据给组件
export const getCates = (state) => state.Cate.cate;
export const getN = (state) => state.Cate.n;
export const getGoods = (state) => state.Cate.goods;

//导出reducer
export default reducer;
